package com.alibaba.citrus.cr.unified.inventory.utils;

import org.apache.commons.lang.time.DateFormatUtils;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Objects;

public class DateUtils {
    public final static String DATE_FORMAT = "yyyy-MM-dd";

    //取本月第一天
    public static Date getStartTimeOfMonth() {
        Calendar startThisMonth = Calendar.getInstance();
        startThisMonth.set(Calendar.DAY_OF_MONTH, 1);
        startThisMonth.set(Calendar.HOUR_OF_DAY, 1);
        return startThisMonth.getTime();
    }
    //取本月第一天
    public static String getStartOfMonthStr() {
        return DateFormatUtils.format(getStartTimeOfMonth(), DATE_FORMAT);
    }
    //取本月最后一天
    public static String getLastOfMonthStr(){
        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.DAY_OF_MONTH, calendar.getActualMaximum(Calendar.DAY_OF_MONTH));
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 0);
        return DateFormatUtils.format(calendar.getTime(), DATE_FORMAT);
    }
    //取本月最后一天
    public static Date getLastTimeOfMonth(){
        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.DAY_OF_MONTH, calendar.getActualMaximum(Calendar.DAY_OF_MONTH));
        return calendar.getTime();
    }

    /**
     * 搜索框时间处理，添加精确时间分区
     * @param date
     * @param begin
     * @return
     */
    public static Date obtainCurrentDayBeginOrEnd(Date date,Boolean begin)  {
        if (Objects.isNull(date)) {
            return null;
        }

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        String dateStr = sdf.format(date);
        if (begin) {
            dateStr = dateStr.split(" ")[0] + " 00:00:00";
        } else {
            dateStr = dateStr.split(" ")[0] + " 23:59:59";
        }
        try {
            return sdf.parse(dateStr);
        } catch (ParseException e) {
            throw new IllegalArgumentException(e.getMessage());
        }

    }

}
